<?php
namespace App\Service;

use \Lcobucci\JWT\Builder;
use \Lcobucci\JWT\Parser;
use \Lcobucci\JWT\Signer\Hmac\Sha256;

class Jwt
{
    public function getToken(array $userData = [])
    {
        $builder    = new Builder();
        $stringOperate = new StringOperate();
        $expireTime = time() + 3600 * 24 * 7;
        $beforeTime = time();
        $createTime = time();
        //设置header和payload，以下的字段都可以自定义

        //发布者
        $builder->setIssuer(JWT['iss']);

        //接收者
        $builder->setAudience(JWT['aud']);

        //对当前token设置的标识
        $builder->setId(md5(time() . http_build_query($userData) . $stringOperate->get_random_str(14)), true);

        //token创建时间
        $builder->setIssuedAt($createTime);

        //过期时间
        $builder->setExpiration($expireTime);

        //当前时间在这个时间前，token不能使用
        $builder->setNotBefore($beforeTime);

        //自定义数据
        foreach ($userData as $key => $value) {
            $builder->set($key, $value);
        }


        //设置签名
        $builder->sign(new Sha256(), JWT['secret']);

        //获取加密后的token，转为字符串
        return (string) $builder->getToken();
    }

    public function verify(string $token, $checkExpire = true)
    {

        try {

            //解析token
            $parse = (new Parser())->parse($token);

            //验证token合法性
            if (! $parse->verify(new Sha256(), JWT['secret'])) {
                return false;
            }

            //验证是否已经过期
            if ($checkExpire && $parse->isExpired()) {
                return false;
            }

            //获取数据
            return array_map(function ($value) {
                return $value->getValue();
            }, $parse->getClaims());

        } catch (\Throwable $e) {
            return false;
        }
    }

}